package com.zilue.hfqueue.channel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by ZD on 2017/6/1.
 */
public class RequestHandler implements Runnable {
    private SocketChannel socketChannel;
    private static final String CHARSET_NAMR = "utf-8";
    private static AtomicLong requestTime=new AtomicLong(0);
    private static AtomicLong processTime=new AtomicLong(0);

    public RequestHandler(final SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {
        requestTime.addAndGet(1);
        long start = System.nanoTime() ;
        try {
            ByteBuffer buffer = ByteBuffer.allocate(64);
            try {
                Message message = MessageHandler.parseMessage(socketChannel);
                System.out.println("接收消息：" + message);
                buffer.putInt(MessageStatus.success.getStatus());
                buffer.put("receive success!".getBytes(CHARSET_NAMR));
                buffer.flip();
                while (buffer.hasRemaining())
                    socketChannel.write(buffer);
            } catch (MessageParseException e) {
                buffer.clear();
                buffer.putInt(MessageStatus.failed.getStatus());
                buffer.put(e.getMessage().getBytes(CHARSET_NAMR));
                buffer.flip();
                socketChannel.write(buffer);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            try {
                if (socketChannel.isConnected())
                    socketChannel.finishConnect();

                long use_time = System.nanoTime() - start;
                processTime.addAndGet(use_time);
                showPerRequestTime();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void showPerRequestTime(){
        System.out.println("平均请求："+processTime.doubleValue()/requestTime.doubleValue()/(1e6));
    }

}
